// pages/favorites/favorites.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    favorites: [],
    loading: false,
    noMore: false,
    isEditMode: false,
    selectedItems: {},
    isAllSelected: false,
    page: 1,
    pageSize: 10,
    showPopup: false,
    currentRestaurant: null,
    myRating: 0,
    isLoggedIn: false,
    userInfo: null,
    pageShakeAnimation: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    if (this.data.isLoggedIn) {
      this.loadFavorites();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo || null
    });
  },

  /**
   * 处理用户登录
   */
  handleLogin() {
    wx.showLoading({
      title: '登录中...',
    });

    // 使用API模块的自动登录
    const api = require('../../utils/api.js');
    api.autoLogin().then(token => {
      if (token) {
        console.log('登录成功:', token);
        const userInfo = {
          nickName: '用户' + Math.floor(Math.random() * 1000000),
          avatarUrl: api.baseUrl.replace('/api/v1', '') + '/icons/avatar-sample.png'
        };

        wx.setStorageSync('userInfo', userInfo);

        this.setData({
          isLoggedIn: true,
          userInfo: userInfo
        });

        wx.hideLoading();
        this.loadFavorites();
      } else {
        console.error('登录失败');
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('登录请求失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '登录请求失败',
        icon: 'none'
      });
    });
  },

  /**
   * 处理用户退出登录
   */
  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('userInfo');

          this.setData({
            isLoggedIn: false,
            userInfo: null,
            favorites: [],
            isEditMode: false
          });

          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  /**
   * 加载收藏列表
   */
  loadFavorites() {
    if (!this.data.isLoggedIn) return;

    const { page, pageSize } = this.data;
    this.setData({ loading: true });

    // 使用API模块而不是直接请求
    const api = require('../../utils/api.js');
    api.getFavorites({
      page,
      pageSize
    }).then(res => {
      if (res.code === 0) {
        const restaurantList = res.data.restaurants || [];
        const noMore = restaurantList.length < pageSize;

        this.setData({
          favorites: page === 1 ? restaurantList : [...this.data.favorites, ...restaurantList],
          loading: false,
          noMore
        });
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: res.message || '获取收藏列表失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取收藏列表失败:', err);

      // 处理401未授权的情况
      if (err.statusCode === 401) {
        this.setData({
          isLoggedIn: false,
          userInfo: null,
          loading: false
        });

        wx.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none'
        });
        return;
      }

      // 加载模拟数据用于测试
      this.setData({ loading: true });
      setTimeout(() => {
        const mockData = [
          {
            id: 1,
            name: "川湘居",
            location: "西湖区文三路478号",
            fullAddress: "杭州市西湖区文三路478号文三数码大厦1层",
            nearestSubway: "2号线-学院路站D出口步行350米",
            userAverageScore: 4.8,
            userReviewCount: 246,
            officialScore: 4.6,
            averagePrice: 88,
            businessHours: "周一至周日 11:00-21:30",
            officialReview: "这是一家正宗湖南菜餐厅，主打各类辣味湘菜。招牌菜有剁椒鱼头、干锅肥肠和小炒黄牛肉。食材新鲜，做工精细，深受本地食客喜爱。",
            tags: ["川菜", "辣味", "人气榜"],
            isFavorite: true
          },
          {
            id: 2,
            name: "杭帮小馆",
            location: "西湖区余杭塘路969号",
            fullAddress: "杭州市西湖区余杭塘路969号万塘汇商场2层",
            nearestSubway: "4号线-余杭塘路站A出口步行150米",
            userAverageScore: 4.6,
            userReviewCount: 187,
            officialScore: 4.5,
            averagePrice: 62,
            businessHours: "周一至周日 10:30-21:00",
            officialReview: "这家餐厅专注于传统杭帮菜，口味地道，环境温馨。招牌菜西湖醋鱼、龙井虾仁和东坡肉都做得相当考究，价格实惠，非常适合家庭聚餐。",
            tags: ["杭帮菜", "本地特色"],
            isFavorite: true
          },
          {
            id: 3,
            name: "粤香阁",
            location: "滨江区滨盛路1508号",
            fullAddress: "杭州市滨江区滨盛路1508号海亮滨盛广场3层",
            nearestSubway: "1号线-滨和路站D出口步行500米",
            userAverageScore: 4.7,
            userReviewCount: 312,
            officialScore: 4.8,
            averagePrice: 118,
            businessHours: "周一至周日 11:00-14:00, 17:00-21:30",
            officialReview: "这是一家高档粤菜馆，环境优雅，服务周到。主厨有超过20年的经验，擅长各类海鲜烹饪。推荐招牌菜白灼虾、脆皮烧鹅和各类点心。适合商务宴请。",
            tags: ["粤菜", "海鲜", "高档"],
            isFavorite: true
          },
          {
            id: 4,
            name: "江南食府",
            location: "上城区平海路128号",
            fullAddress: "杭州市上城区平海路128号",
            nearestSubway: "2号线-建国北路站C出口步行400米",
            userAverageScore: 4.5,
            userReviewCount: 156,
            officialScore: 4.4,
            averagePrice: 75,
            businessHours: "周一至周日 11:00-21:00",
            officialReview: "这家餐厅主打江浙菜系，装修风格古朴典雅，菜品追求本味。招牌菜有西湖醋鱼、叫花鸡和宋嫂鱼羹，很好地展现了江南本土风味。",
            tags: ["江浙菜", "家常菜"],
            isFavorite: true
          },
          {
            id: 5,
            name: "老鸭煲",
            location: "拱墅区莫干山路100号",
            fullAddress: "杭州市拱墅区莫干山路100号蓝钻天成底商",
            nearestSubway: "1号线-莫干山路站B出口步行250米",
            userAverageScore: 4.9,
            userReviewCount: 423,
            officialScore: 4.7,
            averagePrice: 92,
            businessHours: "周一至周日 11:00-22:00",
            officialReview: "这家特色小吃店主打老鸭煲，选用本地放养的麻鸭，配以十多种中药材和青笋、菌菇等食材炖煮8小时。汤色奶白，鸭肉鲜嫩，是寒冷冬天的首选暖胃美食。",
            tags: ["特色小吃", "人气王"],
            isFavorite: true
          }
        ];

        const noMore = mockData.length < pageSize;

        this.setData({
          favorites: page === 1 ? mockData : [...this.data.favorites, ...mockData],
          loading: false,
          noMore
        });
      }, 800);
    });
  },

  /**
   * 切换编辑模式
   */
  toggleEditMode() {
    this.setData({
      isEditMode: !this.data.isEditMode,
      selectedItems: {},
      isAllSelected: false
    });
  },

  /**
   * 切换选择单个项目
   */
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const selectedItems = { ...this.data.selectedItems };

    if (selectedItems[id]) {
      delete selectedItems[id];
    } else {
      selectedItems[id] = true;
    }

    const isAllSelected = this.data.favorites.length > 0 &&
      this.data.favorites.every(item => selectedItems[item.id]);

    this.setData({
      selectedItems,
      isAllSelected
    });
  },

  /**
   * 切换全选/全不选
   */
  toggleSelectAll() {
    const { favorites, isAllSelected } = this.data;
    let selectedItems = {};

    if (!isAllSelected) {
      favorites.forEach(item => {
        selectedItems[item.id] = true;
      });
    }

    this.setData({
      selectedItems,
      isAllSelected: !isAllSelected
    });
  },

  /**
   * 批量删除选中项目
   */
  batchDelete() {
    const { selectedItems, favorites } = this.data;
    const selectedIds = Object.keys(selectedItems).map(Number);

    if (selectedIds.length === 0) {
      wx.showToast({
        title: '请先选择要删除的项目',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认删除',
      content: `确定要移除${selectedIds.length}个收藏吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...',
            mask: true
          });

          // 使用API模块批量删除收藏
          const api = require('../../utils/api.js');
          api.batchDeleteFavorites(selectedIds).then(res => {
            wx.hideLoading();

            if (res.code === 0) {
              // 从页面数据中移除已删除的项目
              const newFavorites = favorites.filter(item => !selectedIds.includes(item.id));

              this.setData({
                favorites: newFavorites,
                selectedItems: {},
                isAllSelected: false,
                isEditMode: newFavorites.length > 0 ? this.data.isEditMode : false
              });

              wx.showToast({
                title: `成功删除${res.data.deletedCount}个收藏`,
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: res.message || '批量删除失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            wx.hideLoading();
            console.error('批量删除失败:', err);
            wx.showToast({
              title: '批量删除失败',
              icon: 'none'
            });
          });
        }
      }
    });
  },

  /**
   * 取消收藏
   */
  unfavorite(e) {
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '取消收藏',
      content: '确定要取消收藏此餐厅吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中...'
          });

          // 使用API模块取消收藏
          const api = require('../../utils/api.js');
          api.toggleFavorite(id, false).then(res => {
            wx.hideLoading();

            if (res.code === 0) {
              // 从页面数据中移除已取消收藏的项目
              const newFavorites = this.data.favorites.filter(item => item.id !== id);

              this.setData({
                favorites: newFavorites
              });

              // 添加页面震动效果
              this.setData({
                pageShakeAnimation: true
              });

              // 添加设备震动反馈
              wx.vibrateShort({
                type: 'medium'
              });

              // 500毫秒后取消震动动画
              setTimeout(() => {
                this.setData({
                  pageShakeAnimation: false
                });
              }, 500);

              wx.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: res.message || '取消收藏失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            wx.hideLoading();
            console.error('取消收藏失败:', err);
            wx.showToast({
              title: '取消收藏失败，请稍后再试',
              icon: 'none'
            });
          });
        }
      }
    });
  },

  /**
   * 查看餐厅详情
   */
  goToDetail(e) {
    if (this.data.isEditMode) return;

    const id = e.currentTarget.dataset.id;
    const restaurant = this.data.favorites.find(item => item.id === id);

    if (restaurant) {
      const restaurantCopy = JSON.parse(JSON.stringify(restaurant));

      this.setData({
        showPopup: true,
        currentRestaurant: restaurantCopy,
        myRating: 0
      });
    }
  },

  /**
   * 跳转到排行榜页面
   */
  goToRanking() {
    wx.switchTab({
      url: '/pages/ranking/ranking'
    });
  },

  /**
   * 加载更多
   */
  loadMore() {
    if (this.data.loading || this.data.noMore) return;

    this.setData({
      page: this.data.page + 1
    }, () => {
      this.loadFavorites();
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      page: 1,
      favorites: [],
      noMore: false
    }, () => {
      this.loadFavorites();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 隐藏餐厅详情弹窗
   */
  hideDetailPopup() {
    this.setData({
      showPopup: false
    });
  },

  /**
   * 给餐厅评分
   */
  rateRestaurant(e) {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const score = e.currentTarget.dataset.score;
    const oldScore = this.data.myRating;
    const restaurantId = this.data.currentRestaurant.id;

    // 如果点击的是已选中的星星，取消评分
    const newScore = oldScore === score ? 0 : score;

    this.setData({
      myRating: newScore
    });

    wx.showLoading({
      title: '提交中...'
    });

    const api = require('../../utils/api.js');

    if (newScore > 0) {
      // 提交评分到服务器
      api.rateRestaurant(restaurantId, newScore).then(res => {
        wx.hideLoading();

        if (res.code === 0) {
          // 更新餐厅信息
          const currentRestaurant = { ...this.data.currentRestaurant };
          currentRestaurant.userAverageScore = res.data.userAverageScore;
          currentRestaurant.userReviewCount = res.data.userReviewCount;
          currentRestaurant.myRating = res.data.myRating;

          this.setData({
            currentRestaurant
          });

          // 更新列表中的数据
          const favorites = [...this.data.favorites];
          const index = favorites.findIndex(item => item.id === restaurantId);
          if (index !== -1) {
            favorites[index].userAverageScore = res.data.userAverageScore;
            favorites[index].userReviewCount = res.data.userReviewCount;

            this.setData({
              favorites
            });
          }

          wx.showToast({
            title: `评分成功: ${newScore}星`,
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.message || '评分失败',
            icon: 'none'
          });
          // 恢复原评分
          this.setData({ myRating: oldScore });
        }
      }).catch(err => {
        wx.hideLoading();
        console.error('评分失败:', err);
        wx.showToast({
          title: '评分失败，请稍后再试',
          icon: 'none'
        });
        // 恢复原评分
        this.setData({ myRating: oldScore });
      });
    } else {
      // 删除评分
      api.deleteRating(restaurantId).then(res => {
        wx.hideLoading();

        if (res.code === 0) {
          // 更新餐厅信息
          const currentRestaurant = { ...this.data.currentRestaurant };
          currentRestaurant.userAverageScore = res.data.userAverageScore;
          currentRestaurant.userReviewCount = res.data.userReviewCount;
          currentRestaurant.myRating = 0;

          this.setData({
            currentRestaurant
          });

          // 更新列表中的数据
          const favorites = [...this.data.favorites];
          const index = favorites.findIndex(item => item.id === restaurantId);
          if (index !== -1) {
            favorites[index].userAverageScore = res.data.userAverageScore;
            favorites[index].userReviewCount = res.data.userReviewCount;

            this.setData({
              favorites
            });
          }

          wx.showToast({
            title: '已取消评分',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.message || '取消评分失败',
            icon: 'none'
          });
          // 恢复原评分
          this.setData({ myRating: oldScore });
        }
      }).catch(err => {
        wx.hideLoading();
        console.error('取消评分失败:', err);
        wx.showToast({
          title: '取消评分失败，请稍后再试',
          icon: 'none'
        });
        // 恢复原评分
        this.setData({ myRating: oldScore });
      });
    }
  },

  /**
   * 导航到餐厅位置
   */
  navigateToRestaurant() {
    const restaurant = this.data.currentRestaurant;

    const latitude = 30.25 + Math.random() * 0.05;
    const longitude = 120.15 + Math.random() * 0.05;

    wx.openLocation({
      latitude,
      longitude,
      name: restaurant.name,
      address: restaurant.fullAddress || restaurant.location,
      scale: 18
    });

    wx.showToast({
      title: '正在导航...',
      icon: 'success'
    });
  },

  /**
   * 图片预览功能
   */
  previewImage(e) {
    const src = e.currentTarget.dataset.src;
    if (!src) {
      wx.showToast({
        title: '无法预览图片',
        icon: 'none'
      });
      return;
    }

    wx.previewImage({
      current: src, // 当前显示图片的链接
      urls: [src] // 需要预览的图片链接列表
    });
  },
})